<?php

// header('content-type:text/html; charset=utf-8');
$servername = "localhost";
$username = "root";
$password = "020913";
$dbname = "demo"; // 数据库名称

$mysqli = new mysqli($servername, $username, $password, $dbname);
if($mysqli->connect_error){
    die("连接失败: ".$conn->connect_error);
}
$mysqli->set_charset('utf8'); // 设置字符集

// 根据设置的主键 uid 查：
// // 预处理语句，后面的 ？，也是为了防止黑客的攻击
// $sql = "SELECT username, age, gender FROM demo1 WHERE uid = ?";
// $mysqli_stmt = $mysqli->prepare($sql);
// // 要查询的 uid
// $uid = 1;
// $mysqli_stmt->bind_param('i', $uid);

// 根据年龄查：
// 预处理语句，后面的 ？，也是为了防止黑客的攻击
$sql = "SELECT username, age, gender FROM demo1 WHERE age = ?";
$mysqli_stmt = $mysqli->prepare($sql);
// 要查询的 age
$age = 28;
$mysqli_stmt->bind_param('i', $age);

// 执行预处理语句
if($mysqli_stmt->execute()){
    // bind_result() 绑定结果集中的值到变量
    $mysqli_stmt->bind_result($username, $age, $gender);
    // 遍历结果集
    while($mysqli_stmt->fetch()){
        echo "姓名：" . $username . "<br>";
        echo "年龄：" . $age . "<br>";
        $gender = $gender == 1 ? '女' : '男';
        echo "性别：" . $gender . "<br>";

        echo "<br>";
    }
}

// 释放结果集
$mysqli_stmt->free_result();
$mysqli_stmt->close();
$mysqli->close(); 

